package com.atguigui.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 890.查找和替换模式
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/6/12 09:54
 */
public class P890FindAndReplacePattern {
    public static void main(String[] args) {
        Solution solution = new P890FindAndReplacePattern().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<String> findAndReplacePattern(String[] words, String pattern) {

            List<String> list = new ArrayList<>();
            for (String word : words) {
                if (match(word, pattern) && match(pattern, word)) {
                    list.add(word);
                }
            }

            return list;
        }

        /**
         * 两个单词之间转换
         *
         * @param word
         * @param pattern
         * @return
         */
        private boolean match(String word, String pattern) {

            Map<Character, Character> map = new HashMap<>();
            for (int i = 0; i < word.length(); i++) {
                char x = word.charAt(i), y = pattern.charAt(i);
                if (!map.containsKey(x)) {
                    map.put(x, y);
                } else if (map.get(x) != y) { // word 中的同一字母必须映射到 pattern 中的同一字母上
                    return false;
                }
            }

            return true;
        }
    }
}
